#!/bin/sh

#
# Copyright 2016 Caglio Giuliano
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
#
#
# Wrapper for SAR command to allow direct use of the output
# in PowerBI sheets for diagnostics, troubleshooting or
# capacity planning purposes
#
# Version 1.1 - added support for "-f" parameter to parse already existing safile
#               forced H24 time format to avoid problem with the timestamp from the safile



# customize with your locale for the correct PowerBI date/time/numeric interpretation
mylocale_LC_ALL="it_IT"

# ----------------------------------------------------

# modify current locale based on the customization
old_LCALL=$LC_ALL
if [ ! -z $mulocale_LCALL ]; then
  export LC_ALL=$mylocale_LC_ALL
fi

# override time string with 24H format
old_LCTIME=$LC_TIME
export LC_TIME='C'



# iterate over all command line parameters
data_from_safile=0
source_safile="";
date_safile="";

for p in "$@"
do

  if [ $data_from_safile -gt 0 ]; then
    if [ -z $source_safile ]; then
      source_safile=$p

      # safile are rotated daily. I will get the correct date from the safile directly
      date_safile=$(stat --format=%Y $source_safile | xargs -I{} date -d @{}  +"%Y-%m-%d")

    fi
  fi

  if [ "X$p" = "X-f" ]; then
    data_from_safile=1
  fi


done





sar $@ | grep --line-buffered  -i -v "$(hostname)" |  awk -v fileDate="$date_safile" -v hostname="$(hostname)" 'BEGIN{ prev_is_blank=0; headings[""]=""; }{

      if ($1=="Average:") {
        next ;
      }

      if (prev_is_blank>0 && length($0)>0){

        prev_is_blank=0;

        ref=$2$3$4$5;
        if ( ref in headings ){
          next;
        }else{
          headings[ref]="dummy";
        }


        printf "hostname;datetime";
        for ( i=2; i<=NF; i++){
          printf "%s", ";"$i;
        }
        printf "\n";
      }else if (prev_is_blank==0 && length($0)>0 ){

        if ( length(fileDate)>0 ){
          printf hostname ";" fileDate " " $1;
        }else{
          printf hostname ";" strftime("%Y-%m-%d %H:%M:%S");
        }


        for ( i=2; i<=NF; i++){
          printf "%s", ";"$i;
        }

        printf "\n";
      }


      if ( length($0)==0 ){
        prev_is_blank=1;
      }

}'


export LC_ALL=$old_LCALL
export LC_TIME=$old_LCTIME